##########################################
## Copyright 2012 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import gi
gi.require_version('Gst', '1.0')
import os
import wave
import urllib.request as url
from gi.repository import Gst
from gi.repository import GstPbutils


def getDuration(path):
    ext = extension(path)
    if(ext == '.wav' or ext == '.wave'):
        return waveDuration(path)
    else:
        return gstDuration(path)


def extension(path):
    return os.path.splitext(path)[-1].lower()


def waveDuration(path):
    try:
        f = wave.open(path, 'r')
        frames = f.getnframes()
        rate = f.getframerate()
        f.close()
        return int(frames / float(rate) * 1000)
    except:
        return -1


def gstDuration(path):
    try:
        disc = GstPbutils.Discoverer()
        discInfo = disc.discover_uri('file://' + url.pathname2url(path))
        return int(discInfo.get_duration() / Gst.MSECOND)
    except:
        return -1
